# Create your views here.

from django.http import HttpResponse
from django.conf.urls.defaults import *
from django.shortcuts import redirect
import json

urlpatterns = patterns('cart.views',
    (r'^add',    'add'),
    (r'^remove',    'remove'),
    (r'^view',    'view'),
    (r'^clear',    'clear'),
    )

def add(request):
    try:
        shopping_cart = json.loads(str(request.session['cart']))
    except KeyError, TypeError:
        shopping_cart = []
    
    product_id = request.GET['product_id']
    title = request.GET['title']
    price = request.GET['price']
    vendor = request.GET['vendor']
    purchase_url = request.GET['purchase_url']
    
    item = {'product_id':product_id,
            'title':title,
            'price':price,
            'index':len(shopping_cart),
            'vendor':vendor,
            'purchase_url': purchase_url }
    
    shopping_cart.append(item)
    
    request.session['cart'] = json.dumps(shopping_cart,indent=4)
    
    return HttpResponse(True)

def remove(request):
    try:
        shopping_cart = json.loads(request.session['cart'])
    except KeyError:
        shopping_cart = []
        
    index = int(request.GET['index'])
    
    item = shopping_cart.pop(index)
    
    request.session['cart'] = json.dumps(shopping_cart)
    
    return HttpResponse(True)
    
def view(request):
    return HttpResponse(request.session['cart'])

def clear(request):
    request.session['cart'] = []
    
    return HttpResponse(True)
